from django.shortcuts import render
from .serializers import CategorySerializer, MovieSerializer
from .models import Movie,Category
from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework import generics,viewsets
from rest_framework import mixins
from rest_framework.response import Response
from django.http import Http404
from rest_framework import status
from django_filters import rest_framework as filters


# Create your views here.
class MovieList(APIView):
    """
    电影列表
    """
    def get(self,request):
        movies=Movie.objects.all()
        serializer=MovieSerializer(movies,many=True)
        return Response(serializer.data)
    def post(self,request):
        serializer=MovieSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors)
    
# class MovieDetail(APIView):
    """
    电影详情
    """
    def get(self,request,pk):
        try:
            movie=Movie.objects.get(id=pk)
        except Movie.DoesNotExist:
            raise Http404
        serializer=MovieSerializer(movie)
        return Response(serializer.data)
    
    def patch(self,request,pk):
        try:
            movie=Movie.objects.get(id=pk)
        except Movie.DoesNotExist:
            raise Http404
        serializer=MovieSerializer(movie,data=request.data,partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data,status=status.HTTP_200_OK)
        return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
    def delete(self,request,pk):
        try:
            movie=Movie.objects.get(id=pk)
        except Movie.DoesNotExist:
            raise Http404
        movie.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

class MovieFilter(filters.FilterSet):
    movie_name = filters.CharFilter(field_name='movie_name', lookup_expr='icontains')
    category_id = filters.NumberFilter(field_name='category_id', lookup_expr='exact')
    region = filters.NumberFilter(field_name='region', lookup_expr='exact')
    
    class Meta:
        model = Movie
        fields = ['movie_name','category_id','region']


class MovieViewset(viewsets.ModelViewSet):
    queryset = Movie.objects.all()
    serializer_class = MovieSerializer
    filter_backends = [filters.DjangoFilterBackend]
    filterset_class = MovieFilter
    
class MovieCategoryViewset(viewsets.ModelViewSet):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    filter_backends = [filters.DjangoFilterBackend]
    pagination_class = None
    

    

